package com.hdq.aspect;

import com.hdq.annotation.AutoFillList;
import com.hdq.annotation.ManagerName;
import com.hdq.constant.AutoFillConstant;
import com.hdq.constant.ManagerNameConstant;
import com.hdq.context.BaseContext;
import com.hdq.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.List;

@Aspect
@Component("managerNameAspect")
@Slf4j
public class ManagerNameAspect {

    @Pointcut("execution(* com.hdq.mapper.*.*(..)) && @annotation(com.hdq.annotation.ManagerName)")
    public void managerNameAspectPointcut() {
    }


    @Before("managerNameAspectPointcut()")
    public void managerNameAspect(JoinPoint joinPoint) {
        log.info("运行{}", joinPoint);

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        ManagerName annotation = signature.getMethod().getAnnotation(ManagerName.class);
        OperationType operationType = annotation.value();

        Object[] args = joinPoint.getArgs();
        if (args.length == 0 || args == null) return;

        Object entity = args[0];
        Long userId = BaseContext.getCurrentId();
        if (operationType == OperationType.INSERT) {
                try {
                    Method setCreateManagerId = entity.getClass().getDeclaredMethod( ManagerNameConstant.SET_CREATE_MANAGER_ID, Long.class);
                    Method setLastUpdateManagerId = entity.getClass().getDeclaredMethod(ManagerNameConstant.SET_LAST_UPDATE_MANAGER_ID,Long.class);

                    setCreateManagerId.invoke(entity, userId);
                    setLastUpdateManagerId.invoke(entity, userId);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else if (operationType == OperationType.UPDATE) {
                try {
                    Method setLastUpdateManagerId = entity.getClass().getDeclaredMethod(ManagerNameConstant.SET_LAST_UPDATE_MANAGER_ID,Long.class);
                    setLastUpdateManagerId.invoke(entity, userId);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
        }
    }

}
